package com.woniuxy.controller;

import com.woniuxy.entity.User;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.service.AuthService;
import com.woniuxy.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    AuthService authService;
    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/login")
    public ResponseEntity login(User user) {
        User dbUser = authService.findUser(user);
        // 校验账号
        if (Objects.nonNull(dbUser) && dbUser.getPassword().equals(user.getPassword())) {
            // 登录成功
            String token = JWTUtils.generateToken(user.getUsername());
            // 存储到redis中，并创建一个refreshToken
            ResponseEntity success = new ResponseEntity(dbUser);
            success.put("token", token);
            // 获取refreshToken存入redis，并设置过期时间
            String refreshToken = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(refreshToken, dbUser, 60, TimeUnit.MINUTES);
            success.put("refreshToken", refreshToken);
            return success;
        }else {
            return ResponseEntity.ERROR;
        }
    }

    // http://localhost:8092/auth/
    @PutMapping("/")
    public ResponseEntity updateUser(@RequestBody User user) {
        return new ResponseEntity(authService.updateUser(user));
    }

    // http://localhost:8092/auth/clearCache
    @DeleteMapping("/clearCache")
    public ResponseEntity clearCache() {
        authService.cleatCache();
        return new ResponseEntity("清除成功！");
    }
}
